from django.shortcuts import redirect
from django.utils.deprecation import MiddlewareMixin


# 自定义中间件（类方式定义，继承 MiddlewareMixin）
class ConfirmLoginMiddleware(MiddlewareMixin):
    """拦截非法请求"""
    def process_request(self, request):
        # 这里面的代码会在请求到达前被预处理
        user = request.COOKIES.get('user_status')  # 获取当前cookie信息中的user
        path = request.path  # 获取当前请求的地址
        print('patch = {}'.format(path))
        # 未登录时只能访问的列表里面的URL地址
        login_path = [
            '/get_count/',
            '/student/student/login/', '/student/student/register/',
            '/student/student/register/check_number/', '/student/student/generate_code/',
            '/student/student/verify_code/',
            '/organization/organization/register/', '/organization/organization/register/check_number/',
            '/organization/organization/login/', '/organization/organization/generate_code/',
            '/organization/organization/verify_code/',
            '/supervisor/supervisor/register/', '/supervisor/supervisor/register/check_number/',
            '/supervisor/supervisor/login/', '/supervisor/supervisor/generate_code/',
            '/supervisor/supervisor/verify_code/', '',
        ]

        if (user != 'is_login') and (path not in login_path):  # 验证到user未登录的情况下还想请求未授权的路径，就跳转到登录界面
            return redirect('student:login')  # 默认未登录跳到学生登录页面

    def process_response(self, request, response):
        # 这里的代码会在响应发出前被处理
        return response
